package com.educatioin.manage.web.productorder.controller;

import com.educatioin.commons.util.AjaxResult;
import com.educatioin.manage.constant.OrderStatus;
import com.educatioin.manage.web.productorder.entity.PayResult;
import com.educatioin.manage.web.productorder.request.ListOrderReq;
import com.educatioin.manage.web.productorder.request.ModifyOrderReq;
import com.educatioin.manage.web.productorder.response.ListOrderRsp;
import com.educatioin.manage.web.productorder.service.ProductOrderService;
import com.educatioin.manage.wechat.service.WeChatOrderService;
import com.educatioin.manage.wechat.service.WeChatPayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangchen on 2018/4/19.
 */
@RestController
@RequestMapping(value = {"/api/order"})
public class ProductOrderController {
    private Logger logger = LoggerFactory.getLogger(ProductOrderController.class);
    @Resource
    private ProductOrderService productOrderService;

    @Resource
    private WeChatPayService weChatPayService;

    @Resource
    private WeChatOrderService weChatOrderService;


    /**
     * 微信支付成功回调接口
     * @return
     */
    @RequestMapping("/payresult")
    @ResponseBody
    public String payVerify(HttpServletRequest request, HttpServletResponse response){
        logger.info("payVerifyBegin");
        Map<String, String> returnMap = new HashMap<>();
        try {

            String inputLine;
            String notityXml = "";
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            //微信给返回的东西
            try {
                while ((inputLine = request.getReader().readLine()) != null) {
                    notityXml += inputLine;
                }
                request.getReader().close();
            } catch (Exception e) {
                e.printStackTrace();
                returnMap.put("fail", "xml获取失败");
                return WXPayUtil.mapToXml(returnMap);
            }
            if (StringUtils.isEmpty(notityXml)) {
                returnMap.put("fail", "xml为空");
                return WXPayUtil.mapToXml(returnMap);
            }
            PayResult payResult = weChatPayService.validatePayResult(notityXml);

            //订单支付成功
            if ("SUCCESS".equals(payResult.getResultCode())) {
                //更改订单为已支付定金
                weChatOrderService.updateOrderStatus(payResult.getOutTradeNo(), OrderStatus.ORDERED.name());
                returnMap.put("return_code", "SUCCESS");
                returnMap.put("return_msg", "OK");
            } else {
                //订单支付失败
                //toDO
                returnMap.put("return_code", "FAIL");
                returnMap.put("return_msg", payResult.getReturnMsg());
            }
            logger.info(returnMap.toString());
            //无论如何都要返回回调处理结果以免重复通知
            return WXPayUtil.mapToXml(returnMap);
        }catch (Exception e){
            logger.error("payresult fail,reason:" + getStackTrace(e));
            returnMap.put("fail", "xml获取失败");
            return returnMap.toString();
        }
    }

    @RequestMapping("/list")
    @ResponseBody
    public ListOrderRsp list(ListOrderReq req) {
        return productOrderService.list(req);
    }

    @RequestMapping("/modify")
    @ResponseBody
    public AjaxResult modify(@RequestBody ModifyOrderReq req) {
        AjaxResult result = new AjaxResult<>();
        productOrderService.modify(req);
        result.setCode(AjaxResult.SUCCESS_CODE);
        result.setMsg("modify success");
        return result;
    }

    /**
     * 关闭订单（未支付订单）
     * @param id
     * @return
     */
    @RequestMapping("/close")
    @ResponseBody
    public AjaxResult close(Long id) {
        return productOrderService.close(id);
    }

    /**
     * 已付清所有费用
     * @param id
     * @return
     */
    @RequestMapping("/payAll")
    @ResponseBody
    public AjaxResult payAll(Long id) {
        return productOrderService.payAll(id);
    }

    /**
     * 订单完成
     * @param id
     * @return
     */
    @RequestMapping("/complete")
    @ResponseBody
    public AjaxResult complete(Long id) {
        return productOrderService.complete(id);
    }

    @RequestMapping("/findById")
    @ResponseBody
    public AjaxResult findById(Long id) {
        AjaxResult result = new AjaxResult<>();
        result.setData(productOrderService.findById(id));
        result.setCode(AjaxResult.SUCCESS_CODE);
        result.setMsg("success");
        return result;
    }

    /**
     * 完整的堆栈信息
     *
     * @param e Exception
     * @return Full StackTrace
     */
    private static String getStackTrace(Exception e) {
        StringWriter sw = null;
        PrintWriter pw = null;
        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            pw.flush();
            sw.flush();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }
        return sw.toString();
    }
}
